/**
 * 导入模块
 */
import NProgress from 'nprogress';
import { createRouter, createWebHistory } from 'vue-router';

/**
 * 导入类型声明
 */
import type {
  NavigationGuardNext,
  RouteLocationNormalizedGeneric,
  RouteLocationNormalizedLoadedGeneric,
  RouteRecordRaw,
  Router,
} from 'vue-router';

/**
 * 导入子模块
 */
import index from '@/router/modules/index';

/**
 * 获取路由配置
 * @returns
 */
function getRouterConf(): Array<RouteRecordRaw> {
  const routes: Array<RouteRecordRaw> = [
    {
      path: '/',
      redirect: '/index',
    },
    index,
  ];
  return routes;
}

/**
 * 路由器
 */
const router: Router = createRouter({
  // history 模式
  history: createWebHistory(),
  // 路由模块
  routes: getRouterConf(),
});

/**
 * 路由钩子函数
 */
router.beforeEach(
  async (
    to: RouteLocationNormalizedGeneric,
    from: RouteLocationNormalizedLoadedGeneric,
    next: NavigationGuardNext,
  ) => {
    NProgress.configure({ showSpinner: false });
    NProgress.start();
    next();
  },
);

/**
 * 错误监控
 */
router.onError((error: Error) => {
  const message: string = error.message || '';
  if (
    message.includes('Failed to fetch dynamically imported module') ||
    message.includes('Importing a module script failed')
  ) {
    window.location.reload();
  }
});

/**
 * 路由钩子函数
 */
router.afterEach(() => {
  NProgress.done();
});

/**
 * 导出路由配置模块
 */
export default router;
